class Utils {

  /**
   * 防止短时间内连续点击
   * fun 点击后的回调方法
   * time 点击间隔时间
   */
  static taping = false
  static fromEvent(fun, time) {
    if (!this.taping) {
      fun();
      this.taping = true
      if (typeof time !== "number") {
        time = 1000;
      }
      setTimeout(() => this.taping = false, time)
    }
  }

  static second = 60;
  static time;
  // 倒计时
  static countdown(that) {
    if (this.second < 60) {
      return;
    }
    this.time = setInterval(function() {
      this.second = this.second - 1;
      that.setData({
        showTime: this.second == 0 ? "重新获取" : this.second + "s重新获取"
      });
      if (second == 0) {
        clearInterval(this.time);
        second = 60;
      }
    }, 1000);
  }

  // 消除倒计时
  static clearCountdown(that) {
    this.second = 60;
    clearInterval(this.time);
    that.setData({
      showTime: "获取验证码"
    });
  }

  /**
   * 获取屏幕宽高
   */
  static windowSize() {
    var windowSize = {};
    //获取屏幕宽高  
    wx.getSystemInfo({
      success: function(res) {
        var windowWidth = res.screenWidth;
        var windowHeight = res.screenHeight;
        windowSize.winWidth = windowWidth;
        windowSize.winHeight = windowHeight;
      }
    })
    return windowSize;
  }

  //数字小数点后两位
  static isNumber(value) {
    var patrn = /^(-)?\d+(\.\d+)?$/;
    if (patrn.exec(value) == null || value == "") {
      return false
    }
    var point = value.toString().indexOf(".");
    if (point > -1) {
      var length = value.toString().split(".")[1].length;
      //数字小数点后有几位
      if (length > 2) {
        return false;
      }
    }
    return true
  }

  //数组去重
  static unique2(array) {
    var n = {},
      r = [],
      len = array.length,
      val, type;
    for (var i = 0; i < array.length; i++) {
      val = array[i];
      type = typeof val;
      if (!n[val]) {
        n[val] = [type];
        r.push(val);
      } else if (n[val].indexOf(type) < 0) {
        n[val].push(type);
        r.push(val);
      }
    }
    return r;
  }


  static isCard(card) {
    // 11 - 15 京 津 冀 晋 蒙
    // 21 - 23 辽 吉 黑
    // 31 - 37 沪 苏浙 皖 闽 赣 鲁
    // 41 - 46 豫 鄂 湘 粤 桂 琼
    // 50 - 54 渝 川 贵 云 藏
    // 61 - 65 陕 甘青 宁 新
    // 81 - 82 港 澳 
    // 加权因子
    let factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    // 验证码
    let verfiy = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2];
    // 身份证号分解为18位数组
    let cardArray = card.split('');
    // 获取身证号最后一位
    let last = card.substring(17, 18);

    let regStr = /^(((1[1-5])|(2[1-3])|(3[1-7])|(4[1-6])|(5[0-4])|(6[1-5])|(8[1-2]))\d{15})([0-9]|X|x)$/;
    if (!regStr.test(card)) {
      return false;
    }

    // 加权因子分别与身证号对应号相乘并求和
    let sum = 0;
    for (let i = 0; i < factor.length; i++) {
      sum += factor[i] * cardArray[i];
    }
    // verfiy[sum % 11]为身份证号最后一位
    if (last != verfiy[sum % 11]) {
      return false;
    }

    return true;
  }

  static isTelNum(phone) {
    let regStr = /^(1[3-9]\d{9})$/;
    if (!regStr.test(phone)) {
      return false;
    }
    return true;
  }

  /**
   * 排序(大的在高)
   */
  static compareDes(prop) {
    return function(obj1, obj2) {
      var val1 = obj1[prop];
      var val2 = obj2[prop];
      if (val1 > val2) {
        return -1;
      } else if (val1 < val2) {
        return 1;
      } else {
        return 0;
      }
    }
  }

  /**
   * 排序(小的在上)
   */
  static compare(prop) {
    return function(obj1, obj2) {
      var val1 = obj1[prop];
      var val2 = obj2[prop];
      if (val1 < val2) {
        return -1;
      } else if (val1 > val2) {
        return 1;
      } else {
        return 0;
      }
    }
  }


  /**
   * 排序(按名称排)
   */
  static compareName(prop) {
    return function(obj1, obj2) {
      var val1 = obj1[prop];
      var val2 = obj2[prop];
      return val1.localeCompare(val2, 'zh-Hans-CN');
    }
  }

  /**
   * 过滤掉输入的表情
   */
  static filterEmoji(e) {
    let val = e.detail.value;
    let reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g
    if (!reg.test(val)) {
      return
    }

    if (val.match(reg)) {
      val = val.replace(reg, '');
    }

    return val
  }

  /**
   * 过滤掉输入的表情
   */
  static filterEmoji01(value) {
    let arr = []
    let reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g
    for (var i in value) {
      if (!reg.test(value[i])) {
        arr.push(value[i])
      }
    }
    console.log(arr.join(''))

    return arr.join('')
  }

  // static isChinese(temp) {
  //   var re = /[^/u4e00-/u9fa5]/;
  //   if (re.test(temp)) return false;
  //   return true;
  // }


  static chooseLocation(_success) {
    var bmap = require("/bmap-wx.min.js");
    wx.chooseLocation({
      success: function(res) {
        console.log(res)
        var regex = /^(北京市|天津市|重庆市|上海市|香港特别行政区|澳门特别行政区)/;
        var province = [];
        var addressObj = {
          name: res.name,
          province: null,
          city: null,
          district: null,
          address: null,
          latitude: res.latitude,
          longitude: res.longitude
        };

        function regexAddress(address, addressObj) {
          regex = /^(.*?[市州]|.*?地区|.*?特别行政区)(.*?[市区县])(.*?)$/g;
          var addxress = regex.exec(address);
          if (addxress) {
            addressObj.city = addxress[1];
            addressObj.district = addxress[2];
            addressObj.address = addxress[3] + "(" + res.name + ")";
          }
        }
        if (!(province = regex.exec(res.address))) {
          regex = /^(.*?(省|自治区))(.*?)$/;
          province = regex.exec(res.address);
          addressObj.province = province[1];
          regexAddress(province[3], addressObj);
        } else {
          addressObj.province = province[1];
          regexAddress(res.address, addressObj);
        }
        if (addressObj.city) {
          _success(addressObj);
        } else {
          // 百度地图发起regeocoding检索请求 
          var map = new bmap.BMapWX({
            ak: "aAocLeGnlHAOWRge4OyN4CCxPYIXqcwx"
          });
          map.regeocoding({
            location: res.latitude + ',' + res.longitude,
            fail: function(info) {
              console.log(info)
            },
            success: function(location) {
              console.log(location)
              let data = location.originalData.result.addressComponent;
              addressObj.province = data.province;
              addressObj.city = data.city;
              addressObj.district = data.district;
              addressObj.address = data.street + data.street_number;
              _success(addressObj);
            }
          });
        }
      },
      fail: function(err) {
        console.log(err)
      }
    })
  }

  static formatMoney(s, type) {
    if (/[^0-9\.]/.test(s))
      return "0.00";
    if (s == null || s == "null" || s == "")
      return "0.00";
    s = s.toString().replace(/^(\d*)$/, "$1.");
    s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
    s = s.replace(".", ",");
    var re = /(\d)(\d{3},)/;
    while (re.test(s))
      s = s.replace(re, "$1,$2");
    s = s.replace(/,(\d\d)$/, ".$1");
    if (type == 0) {
      var a = s.split(".");
      if (a[1] == "00") {
        s = a[0];
      }
    }
    return s;
  }

  /**
   * 绘制圆角矩形
   * @param {Object} context - canvas组件的绘图上下文
   * @param {Number} x - 矩形的x坐标
   * @param {Number} y - 矩形的y坐标
   * @param {Number} w - 矩形的宽度
   * @param {Number} h - 矩形的高度
   * @param {Number} r - 矩形的圆角半径
   * @param {String} [c = 'transparent'] - 矩形的填充色
   */
  static roundRect(context, x, y, w, h, r, c = 'transparent') {
    if (w < 2 * r) {
      r = w / 2;
    }
    if (h < 2 * r) {
      r = h / 2;
    }

    context.beginPath();
    context.setFillStyle('#fff'); // 这是一个坑，欢迎来跳

    context.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5);
    context.moveTo(x + r, y);
    context.lineTo(x + w - r, y);
    context.lineTo(x + w, y + r);

    context.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2);
    context.lineTo(x + w, y + h - r);
    context.lineTo(x + w - r, y + h);

    context.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5);
    context.lineTo(x + r, y + h);
    context.lineTo(x, y + h - r);

    context.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI);
    context.lineTo(x, y + r);
    context.lineTo(x + r, y);

    context.fill();
    context.closePath();
  }

  /**
   * 绘制圆角图片
   * @param {Object} context - canvas组件的绘图上下文
   * @param {Number} r - 圆角半径
   * @param {String} path - 图片地址
   * @param {Number} sx - 源图像的矩形选择框的左上角 x 坐标
   * @param {Number} sy - 源图像的矩形选择框的左上角 y 坐标
   * @param {Number} sWidth - 源图像的矩形选择框的宽度
   * @param {Number} sHeight - 源图像的矩形选择框的高度
   * @param {String} c - 矩形的填充色
   */
  static roundImage(context, r, path, sx, sy, sWidth, sHeight, c) {
    context.save();
    //context.fillStyle = c
    this.roundRect(context, sx, sy, sWidth, sHeight, r, c);
    context.fill();
    context.clip();
    context.drawImage(path, sx, sy, sWidth, sHeight);
    context.restore();
  }

  /**
   * 自动换行的文本
   * @param {Object} context - canvas组件的绘图上下文
   * @param {String} text - 需要绘制的文本
   * @param {Number} x - 文本左上角 x 坐标
   * @param {Number} y - 文本左上角 y 坐标
   * @param {Number} maxWidth - 最大宽度
   */
  static canvasText(context, text, x, y, maxWidth) {
    var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    context.setFontSize(18)
    context.setFillStyle("#000")
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < maxWidth) {
        temp += chr[a];
      } else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);

    //如果数组长度大于2 则截取前两个
    if (row.length > 2) {
      var rowCut = row.slice(0, 2);
      var rowPart = rowCut[1];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < maxWidth - 60) {
          test += rowPart[a];
        } else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..." //这里只显示两行，超出的用...表示
      rowCut.splice(1, 1, group);
      row = rowCut;
    }
    for (var b = 0; b < row.length; b++) {
      context.fillText(row[b], x, y + b * 30, maxWidth);
    }
  }

  /**
   * 自动换行的文本
   * @param {Object} context - canvas组件的绘图上下文
   * @param {String} text - 需要绘制的文本
   * @param {Number} x - 文本左上角 x 坐标
   * @param {Number} y - 文本左上角 y 坐标
   * @param {Number} maxWidth - 最大宽度
   */
  static canvasText01(context, text, x, y, maxWidth) {
    var chr = text.split(""); //这个方法是将一个字符串分割成字符串数组
    var temp = "";
    var row = [];
    context.setFontSize(12)
    context.setFillStyle("#999999")
    for (var a = 0; a < chr.length; a++) {
      if (context.measureText(temp).width < maxWidth) {
        temp += chr[a];
      } else {
        a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
        row.push(temp);
        temp = "";
      }
    }
    row.push(temp);

    //如果数组长度大于2 则截取前两个
    if (row.length > 1) {
      var rowCut = row.slice(0, 1);
      var rowPart = rowCut[0];
      var test = "";
      var empty = [];
      for (var a = 0; a < rowPart.length; a++) {
        if (context.measureText(test).width < maxWidth - 60) {
          test += rowPart[a];
        } else {
          break;
        }
      }
      empty.push(test);
      var group = empty[0] + "..." //这里只显示两行，超出的用...表示
      rowCut.splice(0, 0, group);
      row = rowCut;
    }
    context.fillText(row[0], x, y, maxWidth);
  }


}


module.exports = Utils;